<?php
namespace app\index\controller;
use app\common\controller\Base;
use think\Db;
use think\Cookie;
use think\cache\driver\Redis;
use app\common\logic\Pocessing;
use GuzzleHttp\json_encode;
use think\Exception;
use app\common\logic\SyxwPayment;

class Processing extends Base
{
    /** ----------------------------------------------------用户相关处理过程Start--------------------------------------------------------- **/
    /**
     * @Purpose 会员登录
     * @Time 2017-11
     */
    public function login()
    {
        $username = input('post.username') ? input('post.username') : '';
        $password = input('post.password') ? input('post.password') : '';
        $code = input('post.code') ? input('post.code') : '';
        if($username && $password && $code) {
            $password = md5($password);
            //查询会员信息
            $result = Db::name('username')->where(['username'=>$username,'password'=>$password])->find();
            if($result['open'] == 1) {
                return 3;
            }
            if($result['sales'] == 1) {
            	return 9;
            }
            /* if($result['dl']) {
                return 2;
            } */
            if(!captcha_check($code)) {
                return 4;
            }
            //处理会员登录
            if($result['id'] > 0) {
                cookie('username',$username);
                cookie('password',$password);
                $login_key = suiji_zifu(15);
                cookie('login_key',$login_key);
                $login_time = time();
                $login_ip = get_ip();
                $zx_list = Db::name('zaixian')->where('username',$username)->find();
                $login_url = $_SERVER['HTTP_HOST'];
                if($zx_list['id'] > 0) {
                    //更新用户在线信息
                    model('Zaixian')->updateOnlineTime($zx_list['id'],$username,$login_time,0,$login_ip,$login_url);
                } else {
                    //插入在线表
                    model('Zaixian')->setOnlineTime($username,$login_time,0,$login_ip,$login_url);
                }
                //会员等级自动提升
//                $us_class = Db::name('us_class')->field('id,czl,xml')->select();
                $usclass = $result['us_class'];
//                foreach ($us_class as $v) {
//                    if($v['czl'] <= $result['czzje']) {
//                        if($v['xml'] <= $result['tzzje']) {
//                            $usclass = $v['id'];
//                        }
//                    }
//                }
                //更新用户登录时间信息及等级
                model('Username')->updateLoginInfo($result['id'],$login_key,$login_time,$usclass,$login_ip);
                Db::name('username')->where('username',$username)->setInc('login_num');
                //记录日志
                $this->caozuoRizhiJilu('2',admin_text(49),$login_ip,$username,1);
                //更新代理下线人数
                $user = Db::name('username')->where(['nbzh'=>0,'swzh'=>0,'open'=>0,'dl'=>1])->select();
                //$user = Db::name('username')->where('nbzh','<',1)->where('swzh','<',1)->where('open','<','1')->select();
                foreach ($user as $val){
                    $user_dl = Db::name('username')->where('tjr',$val['username'])->where('tjrid',$val['id'])->count();
                    $data['xjrens'] = $user_dl;
                    Db::name('username')->where('id',$val['id'])->update($data);
                }
                echo 1;
            } else {
                echo 2;
            }
        } else {
            echo 2;
        }
    }

    /**
     * @Purpose 刷新用户金额
     * @Time 2017-12-01
     */
    public function refreshMoney()
    {
        if(!$this->user_all['login_key']) {
            echo 'out';
        } else {
            echo $this->user_all['je'];
        }
    }

    /**
     * @Purpose 用户退出登录
     * @Time 2017-11
     */
    public function loginOut()
    {
        $url = input('get.url') ? input('get.url') : '';
        //清除登录秘钥
        model('Username')->updateLoginKey($this->user_all['id']);
        Cookie::delete('username');
        Cookie::delete('password');
        Cookie::delete('login_key');
        //删除用户在线时长信息
        model('Zaixian')->delOnlineTime($this->user_all['username']);
        if($url) {
            $url = '/index/'.$url;
        } else {
            $url = '/';
        }
        js_tishi(admin_text(2),$url);
    }

    /**
     * @Purpose 用户修改密码
     * @Time 2017-11-17
     */
    public function updatePass()
    {
        if($this->user_all['id'] < 1) {
            js_tishi('请先登录账号！','/');exit;
        }
        $old_password = input('post.old_password') ? input('post.old_password') : '';
        $new_password = input('post.new_password') ? input('post.new_password') : '';
        $new_password2 = input('post.new_password2') ? input('post.new_password2') : '';
        $passwordclass = input('post.passwordclass') ? input('post.passwordclass') : '';

        //验证密码信息
        if($old_password && $new_password && $new_password2 && $passwordclass) {
            if($passwordclass == '1') {
                $old_password = md5($old_password);
                if($old_password == $this->user_all['password']) {
                    if($new_password == $new_password2) {
                        $new_password = md5($new_password);
                        //记录日志并修改密码
                        $this->caozuoRizhiJilu('2','修改了登录密码',$this->login_ip,$this->user_all['username']);
                        model('Username')->updatePass($this->user_all['username'],$new_password);
                        cookie('username',null);
                        cookie('password',null);
                        cookie('login_key',null);
                        js_tishi('修改成功，请重新登录！','/');
                    } else {
                        js_tishi('新密码不一致！','/index/User/updatePass');
                    }
                } else {
                    js_tishi('旧密码不正确！','/index/User/updatePass');
                }
            } else {
                js_tishi('暂时无法修改支付密码！','/index/User/updatePass');
            }
        } else {
            js_tishi('资料填写不完整！','/index/user/UpdatePass');
        }
    }

    /**
     * @Purpose 用户绑定提现银行卡
     * @Time 2017-12-01
     */
    public function bankBind()
    {
        if($this->user_all['id'] < 1) {
            js_tishi('请先登录账号！','/');exit;
        }
        //试玩账号无法提现
        if($this->user_all['swzh'] == 1) {
            js_tishi('试玩账号无法提现！','/index/User/index');exit;
        }
        $account_holder = input('post.bankren') ? input('post.bankren') : '';
        $account_bank  = input('post.bankname') ? input('post.bankname') : 0;
        $account_number = input('post.bankno') ? input('post.bankno') : '';
        $province = input('post.banksf') ? input('post.banksf') : '';
        $city = input('post.banksq') ? input('post.banksq') : '';
        $mobile = input('post.mobile') ? input('post.mobile') : '';
        $qq = input('post.qq') ? input('post.qq') : '';
        $withdrawal_cipher = input('post.ejmm') ? input('post.ejmm') : '';
        if($account_holder && $account_bank && $account_number && $province && $city && $mobile && $qq && $withdrawal_cipher) {
            $withdrawal_cipher = md5($withdrawal_cipher);
            //绑定用户银行信息
            model('Username')->bindBankInfo($this->user_all['username'],$account_holder,$account_bank,$account_number,$province,$city,$mobile,$qq,$withdrawal_cipher);
            js_tishi('绑定完成！','/index/user/drawMoney');
        } else {
            js_tishi('资料填写不完整！','/index/user/drawMoney');
        }
    }

    /**
     * @Purpose 会员提现
     * @Time 2017-12-01
     */
    public function withdrawDeposit()
    {
        //开启事务
        Db::startTrans();
        if($this->user_all['id'] < 1) {
            js_tishi('请先登录账号！','/');exit;
        }

        $amount = input('post.txje') ? floatval(input('post.txje')) : '';
        $withdrawal_cipher = input('post.ejmm') ? input('post.ejmm') : '';
        if($this->user_all['nbzh'] == 1) {
            alert_back('内部账号不能提现！');
        }
        if($amount && $withdrawal_cipher) {
            //验证二级密码是否正确
            $withdrawal_cipher = md5($withdrawal_cipher);
            if($withdrawal_cipher == $this->user_all['ejmm']) {
                //验证打码量是否满足要求
                $code_amount = Db::name('xt_dmsz')->find();
                if($code_amount['tx_yzdml'] == 1) {
                    if($this->user_all['dml'] > 0) {
                        alert_back("打码量未通过，您还需消费{$this->user_all['dml']}元才能提现！");
                    }
                }
                //提现设定处理
                $draw_set = Db::name('xt_tixian')->find();
                if($draw_set['open'] < 1) {
                    alert_back('提现功能尚未开启！');
                }
                //提现次数判断
                $now_times = date('Y-m-d')." 00:00:00";
                $now_times = strtotime($now_times);
                $count = Db::name('tixian_list')->where('username',$this->user_all['username'])->where('txtime','>',$now_times)->count();
                if($draw_set['txcount'] > 0) {
                    if($count >= $draw_set['txcount']) {
                        alert_back('今日提现次数已用完！');
                    }
                }
                //判断账号是否为冻结或者提现功能是否关闭或者为试玩账号
                if($this->user_all['open']==1 || $this->user_all['swzh']==1 || $this->user_all['tixian_open']==1) {
                    alert_back('您的账号目前为禁止提现状态！');
                }
                //判断提现金额是否满足设置金额
                if($amount<$draw_set['zxje'] || $amount>$draw_set['zdje']) {
                    alert_back("提现金额不能小于{$draw_set['zxje']}，且不能大于{$draw_set['zdje']}");
                }
                if($amount>$this->user_all['je']) {
                    alert_back('您账号金额不足！');
                }
                if($this->user_all['nbzh'] == 1) {
                    $ztin = '1';
                    $caadmin = '系统';
                } else {
                    $ztin = '0';
                    $caadmin = '';
                }
                //事务操作
                try {
                    //插入提现信息
                    model('TixianList')->setDrawInfo($this->user_all['username'],$amount,$ztin,time(),$this->login_ip,$caadmin);
                    //更新用户金额
                    model('Username')->updateMoneyInfo($this->user_all['username'],$amount,'down');
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    alert_back('提现失败请重试！');
                }
                js_tishi('提现成功，等待审核中！','/index/user/drawMoney');
            } else {
                alert_back('提款密码错误！');
            }
        } else {
            alert_back('资料填写不完整！');
        }
    }

    /**
     * @Purpose 会员转账充值处理
     * @Time 2017-12-02
     */
    public function transferAccounts()
    {
        //开启事务
        Db::startTrans();
        if($this->user_all['id'] < 1) {
            js_tishi('请先登录账号！','/');exit;
        }
        //试玩账号无法充值
        if($this->user_all['swzh'] == 1) {
            js_tishi('试玩账号无法充值！','/index/User/index');exit;
        }
        $pay_class = input('post.pay_class') ? input('post.pay_class') : '';
        $account_tmp = input('post.account') ? input('post.account') : '';
        $amount = input('post.amount') ? floatval(input('post.amount')) : 0;
        $words = input('post.words') ? input('post.words') : '';
        $recharge_time = input('post.recharge_time') ? input('post.recharge_time') : '';
        $hy_msje = $hy_msbs = 0;
        
        $tmp = explode('_',$account_tmp);
        
        if(!isset($tmp[1]) || !$tmp[1]) {
            js_tishi('请选择充值账户！','/index/User/recharge');exit;
        }
        $account = $tmp[1];
        
        if(!$pay_class || !$amount || !$words || !$recharge_time) {
            js_tishi('请完善充值信息！','/index/User/recharge');exit;
        }
        if(!strtotime($recharge_time)) {
            js_tishi('请填写正确的充值时间！','/index/User/recharge');exit;
        }
        
        //验证金额
        if($amount <= 0) {
            js_tishi('金额有误请重新输入！','/index/User/recharge');exit;
        }
        if($amount < 10) {
            js_tishi('最低充值金额为十元人民币！','/index/User/recharge');exit;
        }
        if($amount > 99999999) {
            js_tishi('充值金额超过范围！','/index/User/recharge');exit;
        }
        //计算满赠及会员赠送金额
        $sys_cz = Db::name('xt_chongzhi')->find();
        $class_cz = Db::name('us_class')->where('id',$this->user_all['us_class'])->find();
        //会员等级赠送金额
        $hy_zsje = $amount * $class_cz['czzsbl'] / 100;
        $hy_zsbs = $class_cz['czzsbl'];
        if($amount >= $sys_cz['xxcz_je']) {
            //满减金额
            $hy_msje = $amount * $sys_cz['xxcz_zs'] / 100;
            $hy_msbs = $sys_cz['xxcz_zs'];
        }
        //充值防骚扰是否开启，并进行处理
        $count_sheuid = Db::name('xt_czfsr')->find();
        if($count_sheuid['open'] > 0) {
            $nowys = time() - $count_sheuid['time_xx'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$this->user_all['username'])->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                js_tishi("系统充值防骚扰已开启，{$count_sheuid['time_xx']}分钟内只能充值1次！",'/index/User/recharge');
                exit;
            }
        }
        if($this->user_all['nbzh'] == 1) {
            $czzt = 1;
        } else {
            $czzt = 0;
        }
        if($pay_class == 'wx') {
            $xxbank = '微信转账';
            $bankren = Db::name('pay_xxlist')->where('id',$account)->value('xx_bankren');
            $czadmin = '';
        } else if($pay_class == 'ali') {
            $xxbank = '支付宝转账';
            $bankren = Db::name('pay_xxlist')->where('id',$account)->value('xx_bankren');
            $czadmin = '';
        } else if($pay_class == 'bank') {
            $xxbank = '银行转账';
            $bankren = Db::name('pay_xxlist')->where('id',$account)->value('xx_bankren');
            $czadmin = '';
        } else {
            $xxbank = '';
            $bankren = '';
            $czadmin = '';
        }
        //插入转账充值信息
        $ddbh = 'PC_' . time() . rand(000,999);
        try {
            $aa = model('ChongzhiList')->setTransRechargeInfo($ddbh,$amount,$this->user_all['username'],$czzt,'0','2',$xxbank,strtotime($recharge_time),$bankren,$czadmin,$this->login_ip,$czzt,$words,$hy_zsje,$hy_zsbs,$hy_msje,$hy_msbs,$this->user_all['us_class'],'',0,0,$this->user_all['je']);
            if($czzt == 1) {
                //内部账号无需审核
                model('Username')->updateMoneyInfo($this->user_all['username'],$amount,'up');
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
    	    // 回滚事务
    	    Db::rollback();
    	     js_tishi('充值失败请重新提交！','/index/User/recharge');
    	    //return '充值失败请重新提交！';
        }
        js_tishi('提交成功，等待审核中！','/index/User/recharge');
    }

    /** ----------------------------------------------------用户相关处理过程End--------------------------------------------------------- **/

    /**
     * @Purpose 异步读取所有数据
     * @Time 2017-11-23
     */
    public function asyncDataAll()
    {
        $czid = input('czid') ? input('czid') : '';
        if(!$czid) exit;
        
        $ctime = time();
        //读取最新一期
        $redis = new Redis();
        $data_str = $redis->get($czid);
        $data_arr = explode(',', $data_str);
        if(isset($data_arr[1]) && $data_arr[1]>time()) {
            $new_data['qihao'] = $data_arr[0];
            $new_data['jztime'] = $data_arr[1] - $ctime;
        } else {
            $new_data['qihao'] = '加载中...';
            $before_qihao = '加载中...';
            $new_data['jztime'] = 0;
        }
        $shuchucanshu = $new_data['qihao'].'[G]'.$new_data['jztime'];

        //最新一期开奖结果(有数据的最新一期)
        $have_kjjg_str = $redis->get('result_'.$czid);
        $have_kjjg_arr = explode(',', $have_kjjg_str);
        if(isset($have_kjjg_arr[2]) && isset($have_kjjg_arr[0])) {
            $have_kjjg_data['qihao'] = $have_kjjg_arr[0];
            $have_kjjg_data['kjjg'] = kjjg_split($have_kjjg_arr[2],$czid,true);
        } else {
            //Redis无数据时从数据库查询
            $new_kjjg = Db::name('kjjg_list')->where('czid',$czid)->where('jztime','<',$ctime)->where('kjjg','<>','0')->order('jztime','DESC')->find();
            $have_kjjg_data['qihao'] = $new_kjjg['qihao'];
            $have_kjjg_data['kjjg'] = kjjg_split($new_kjjg['kjjg'],$czid,true);
        }
        
        //获取最新一期的上一期期号(无论是否开奖)
        if(!isset($before_qihao)) {
            $before_qihao = $redis->get('secend_'.$czid);
            if(!$before_qihao) {
                $before_qihao = Db::name('kjjg_list')->where('czid',$czid)->where('jztime','<',$ctime)->order('qihao','DESC')->value('qihao');
            }
        }
        //获取最新存在开奖结果的期号
        $shuchucanshu = $shuchucanshu.'[H]'.$have_kjjg_data['qihao'].'[G]'.$have_kjjg_data['kjjg'].'[G]'.$before_qihao;
        //处理系统消息
        $user_msg = 0;
        if($new_data['jztime']) {
            $xitongxiaox = Db::name('xiaoxi')->field('id,test')->where(['username'=>$this->user_all['username'],'ifdq'=>0])->order('id','DESC')->find();
            $count = Db::name('xiaoxi')->where(['username'=>$this->user_all['username'],'ifdq'=>0])->count();
            if($xitongxiaox) $user_msg = "{$count},{$xitongxiaox['test']},{$xitongxiaox['id']}";
        }
        $shuchucanshu = $shuchucanshu.'[H]'.$user_msg;

        /**
         * @todo 获取开奖结果的和值、单双、大小
         */
        $arr = getExtInfo($czid,explode(',',$have_kjjg_data['kjjg']));
        $shuchucanshu = $shuchucanshu.'[H]'.implode('[H]',$arr);
        echo $shuchucanshu;
    }
    /**
     * @Purpose 异步读取开奖数据
     * @Time 2017-11-23
     */
    public function asyncTimeAll(){
        $czid = input('czid',0);
        if( empty($czid) ) exit;
        $obj = new Pocessing();
        $data = $obj->asyncDataAll($czid);
        return json($data);
    }
    public function asyncTimeAll_new(){
    	$czid = input('czid',0);
    	if( empty($czid) ) exit;
    	$obj = new Pocessing();
    	$data = $obj->asyncDataAll_new($czid);
    	return json($data);
    }
    /**
     * @Purpose 异步读取开奖数据
     * @Time 2017-11-23
     */
    public function asyncDataSingle(){
        $czid = input('czid',0);
        if( empty($czid) ) exit;
        $kjjg = Db::name('kjjg_list')->where(['czid'=>$czid])->where('kjjg','<>','0')->order('qihao','DESC')->field('czid,jztime,kjjg,qihao')->find();
        $kjjg['kjjg'] = kjjg_split( $kjjg['kjjg'], $czid );
        $a = 0;
        foreach ( $kjjg['kjjg'] as $ss){$a+=$ss;}
        /* if($czid==36 || $czid==44){
            $kjjg['kjjg'][] = '=';
            $kjjg['kjjg'][] = $a;
        } */
        return json($kjjg);
    }
    public function asyncDataDouble(){
        $ids = input('ids',0);
        if( empty($ids) ) exit;
        $idAttr = json_decode($ids);
        $ret = [];
        $redis = new Redis();

        $caipiao = Db::name('caipai_list')->field("id,cp_name_old,cp_name_new")->select();
        $key_val = [];
        foreach( $caipiao as $v ){
            $key_val[$v['id']] = !empty($v['cp_name_new']) ? $v['cp_name_new'] : $v['cp_name_old'];
        }
        foreach( $idAttr as $v ){
            $key = 'result_'.$v;
            $data = $redis->get($key);
            if( $data ){
                $aAttr = explode(',',$data);
                $b['id'] = $v;
                $b['cp_name'] = $key_val[$v];
                $b['kjjg'] = kjjg_split($aAttr[2], $v);
                $b['qihao'] = $aAttr[0];
                $b['jztime'] = date('Y-m-d H:i',$aAttr[1]);
                $ret[] = $b;
            }
        }
        return json($ret);
    }
    /**
     * @Purpose 追号功能
     * @Time 2017-11-24
     */
    public function chaseNum()
    {
        /*
        1.根据彩种ID判断数据库里今天已经开了多少期（包括未开奖的和正在下注的期数）
        2.用总期数减去已经开了的期数
        3.查询数据库正在下注的期数且当前期数未到截止时间
        4.在正在下注的期数上一直往下加期数，加到剩余期数为止
        */
        $czid = input('czid') ? input('czid') : '';
        $qihao = input('qihao') ? input('qihao') :'';
        if(!$czid || !$qihao) return "发送未知错误！";
        $zhuihao = Db::name('xt_tzms')->value('zhuihao');
        if($zhuihao == 1) {
            //获取已经开出的期数
            $year_now = date('y-m-d',time());
            $new_linux_time = strtotime($year_now." 00:00:00");
            //获取剩余开奖期数
            $count = Db::name('time')->where('czid',$czid)->where('jztime','>',date('H:i:s'))->count();
            $count--;
            $close_time = Db::name('caipai_list')->where('id',$czid)->value('cp_fp_time');
            $new_jztime = time()+$close_time;
            $now_qishu = Db::name('kjjg_list')->where('czid',$czid)->where('jztime','>',$new_jztime)->find();
            /* if($now_qishu['id'] > 0) { */
            //return $now_qishu['qihao'].'[G]'.$count;
            return $qihao.'[G]'.$count;
            /* } else {
                return "截止投注前{$close_time}秒禁止追号！";
            } */
        } else {
            return '追号功能尚未开启！';
        }
    }


    /**
     * @Purpose 消息已阅读
     * @Time 2017-11-24
     */
    public function isRead()
    {
        $tid = input('tid') ? input('tid') : '';
        $ifdq = 1;
    	if($tid > 0) {
    	    $ifdq = 1;
    	    model('Xiaoxi')->updateNotice($tid,$ifdq);
    	} else {
    	    model('Xiaoxi')->updateNotices($this->user_all['username'],$ifdq);
    	}
    }

    /**
     * @Purpose 下注入库
     * @Time 2017-11-29
     */
    public function lotteryBettingStock()
    {
        if(!$this->user_all['id']) {
            return 'notlogin';
        }
        if( 1==intval($this->user_all['touzhu_open']) ){
            return '未开通投注权限';
        }
        //接收参数
        $czid = input('czid') ? intval(input('czid')) : '';
        $number = input('number') ? input('number') : '';
        $play_way = input('play_way') ? input('play_way') : '';
        $periods = input('periods') ? input('periods') : '';
        
        if(!$czid || !$number || !$play_way || !$periods) {
            $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way);
            return '非法操作，已被记录！';
        }
		//-------------------------------------------------期号验证------------------------------------------------------------------//
        
        $qh = Db::name('kjjg_list')->field('qihao')->where(['czid'=>$czid,'jztime'=>['>',time()],'kjjg'=>0,'iftz'=>0])->order('qihao','ASC')->find();
        if($qh['qihao']){
        	if($periods!=$qh['qihao']){
        		$periods = $qh['qihao'];
        		//return '期号出错，请刷新页面';
        	}
        }else{
	       	$qihao = $this->qihaoNext($czid);
	        if($periods!=$qihao[0]){
	        	$periods = $qihao[0];
	        	//return '期号出错，请刷新页面';
	        }
        }
        
        //-------------------------------------------------期号验证------------------------------------------------------------------//
        //验证投注期数是否已经截止投注
        $touzhu_info = Db::name('kjjg_list')->field('jztime,kjjg')->where(['czid'=>$czid,'qihao'=>$periods])->find();
        $close_time = Db::name('caipai_list')->where('id',$czid)->value('cp_fp_time');
        $close_time = $close_time ? $close_time : 30;
        
        /* if(!(($touzhu_info['jztime'] > (time() + $close_time)) && ($touzhu_info['kjjg'] == '0'))) {
            return '已经封盘，请下一期再投！';
        } */
                
        //查询当前彩种返点
        $lottery_type_info = Db::name('lottery_classify')->field('id,fandian')->where("czids REGEXP '(^|,){$czid}($|,)'")->find();
        $fandian = intval($lottery_type_info['fandian']);

        //查询验证所需信息
        $checks = Db::name('play_classify')->alias('pc')
        ->join('__WAY_CLASSIFY__ wc','pc.way_class_id=wc.id')
        ->field('pc.id,pc.min_num,pc.max_num,pc.peilv_ids,pc.max_money')
        ->where('wc.lottery_class_id',$lottery_type_info['id'])
        ->where('pc.class_name_mini',$play_way)
        ->find();

        //定义公共变量
        $all_touzhu_zhushu = 0;
        $all_touzhu_jine = 0;

        /* 验证投注号码格式是否正确 */
        $touzhu_code_hm = explode('[H]',$number);
        foreach($touzhu_code_hm as $yzges) {
            $touzhu_code_danciyz = explode('[SH]',$yzges);
            if(count($touzhu_code_danciyz == 2)) {
                $touzhu_code_1 = explode('[G]',$touzhu_code_danciyz[1]);
                if(count($touzhu_code_1) == 8) {
                    if(!is_numeric($touzhu_code_1[2])) {
                        return '投注金额错误！';
                    }
                    $all_touzhu_jine = $all_touzhu_jine + $touzhu_code_1[2];
                    $touzhu_code_1[0] = trim($touzhu_code_1[0]);
                    $touzhu_code_1[5] = trim($touzhu_code_1[5]);
                    
                    //验证最大投注金额
                    if($checks['max_money']) {
                        $max_money = 0;
                        if($touzhu_code_1[1] == '1') $max_money = $checks['max_money'];
                        if($touzhu_code_1[1] == '2') $max_money = $checks['max_money'] * 10;
                        if($touzhu_code_1[1] == '3') $max_money = $checks['max_money'] * 100;
                        if($touzhu_code_1[4] > $max_money) return "超出单注最大投注金额！";
                    }

                    //获取赔率信息
                    if($checks['id'] != '173' && $checks['id'] != '242') {
                        if(count(explode(',',$checks['peilv_ids'])) == 1) {
                            $peilv_info = Db::name('peilv')->where(['lottery_class_id'=>$lottery_type_info['id'],'id'=>$checks['peilv_ids']])->find();
                        } else {
                            //多赔率组合玩法特殊处理
                            if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16' || $checks['id'] == '188' || $checks['id'] == '204') {
                                $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where('lottery_class_id',$lottery_type_info['id'])->where('id','IN',$checks['peilv_ids'])->select();
                            } else {
                                //六合彩类赔率特殊查询规则
                                if($czid == 9 && $checks['id']) {
                                    if($checks['id'] == '172')  {
                                        $hm_split = explode('_',$touzhu_code_1[0]);
                                        $touzhu_code_1[0] = $hm_split[1];
                                    }
                                    $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'peilv_name'=>$touzhu_code_1[0],'spare'=>$play_way])->find();
                                } else {
                                    $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'peilv_name'=>$touzhu_code_1[0]])->find();
                                }
                            }
                        }
                    }

                    //获取赔率信息(正码过关)
                    if($checks['id'] == '173') {
                        $peilv_info = [];
                        $touzhu_zmgg = explode(',',$touzhu_code_1[0]);
                        $touzhu_zmgg = array_map('trim',$touzhu_zmgg);
                        foreach ($touzhu_zmgg as $v) {
                            $split_zmgg = explode('_',$v);
                            $peilv_info[] = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'spare'=>$play_way])->where('peilv_name',$split_zmgg[1])->find();
                        }
                    }
                    
                    //获取赔率信息(合肖)
                    if($checks['id'] == '242') {
                        $peilv_info = [];
                        $touzhu_hx = explode(' ',$touzhu_code_1[0]);
                        foreach ($touzhu_hx as $v) {
                            if(trim($v)) {
                                $peilv_info[] = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'spare'=>$play_way])->where('peilv_name',$v)->find();
                            }
                        }
                    }
//return $peilv_info;
//return json_encode($peilv_info);
                    //验证赔率
                    if($checks['id'] != '173' && $checks['id'] != '242') {
                        //多赔率组合玩法特殊验证
                        if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16'  || $checks['id'] == '188'  || $checks['id'] == '204') {
                            $peilv_true = '';
                            foreach($peilv_info as $kpi=>$pi) {
                                $peilvs_true = $pi['zdpl'] + ($pi['zgpl'] - $pi['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                                $peilvs_true = sprintf('%.2f',$peilvs_true);
                                $peilv_true .= $peilvs_true . '|';
                            }
                        } else {
                            $peilv_true = $peilv_info['zdpl'] + ($peilv_info['zgpl'] - $peilv_info['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = sprintf('%.2f',$peilv_true);
                        }
                    }
                    
                    if($checks['id'] == '173') {
                        //正码过关验证
                        $peilv_true = 1;
                        foreach ($peilv_info as $k => $v) {
                            $peilv_tmp = $v['zdpl'] + ($v['zgpl'] - $v['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = $peilv_true * $peilv_tmp;
                        }
                        $peilv_true = sprintf('%.2f',$peilv_true);
                    }
                    
                    if($checks['id'] == '242') {
                        //合肖验证
                        $peilv_true = 0;
                        foreach ($peilv_info as $k => $v) {
                            $peilv_tmp = $v['zdpl'] + ($v['zgpl'] - $v['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = $peilv_true + $peilv_tmp;
                        }
                        $peilv_true = $peilv_true / count($peilv_info) / count($peilv_info);
                        $peilv_true = sprintf('%.2f',$peilv_true);
                    }
//return $peilv_true."#".$touzhu_code_1[5];
                    if($peilv_true != $touzhu_code_1[5]) {
                        $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'A1');
                        return '非法操作A1，已被记录！';
                    }
                    
                    $duidehm = ''; //初始化号码验证，必须放在此处
                    //验证号码是否超限
                    $touzhu_code_2 = explode(',',$touzhu_code_1[0]);
                    $touzhu_code_2 = array_map('trim',$touzhu_code_2);

                    if(count($touzhu_code_2) > 1) {
                        foreach($touzhu_code_2 as $yzges_1) {
                            $touzhu_code_3 = explode(' ',$yzges_1);
                            foreach($touzhu_code_3 as $yzges_2) {
                                if((floor($yzges_2)>=$checks['min_num']) && (floor($yzges_2)<=$checks['max_num'])) {
                                    $duidehm .= $yzges_2;
                                }
                            }
                        }
                    } else {
                        if((floor($touzhu_code_2[0])>=$checks['min_num']) && (floor($touzhu_code_2[0])<=$checks['max_num'])) {
                            $duidehm = $touzhu_code_2[0];
                        }
                    }

                    $hm_only = str_replace([',',' '],'',$touzhu_code_1[0]);
                    $duidehm = str_replace([',',' '],'',$duidehm);
//return $hm_only."#".$duidehm;
                    if($duidehm != $hm_only) {
                        $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'A2');
                        return '非法操作A2，已被记录！';
                    }
                }

                //验证投注注数
                $tzzs = touzhu_hm_code_zhushu($checks['id'],$touzhu_code_1[0],$lottery_type_info['id']);
//return $tzzs;
                if(($touzhu_code_1[3] != $tzzs) || !$tzzs) {
                    $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'B');
                    return '非法操作B，已被记录！';
                }
            }
        }
        
        //验证投注金额
        $code_touzhu_jine = touzhuhaoma_jine_code($number);
        if($all_touzhu_jine != $code_touzhu_jine) {
            $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'C');
            return "非法操作C，已被记录！";
        }

        //验证用户金额
        if($this->user_all['je'] < $all_touzhu_jine) {
            return '账号余额不足，请充值后在下注！';
        }
        
        $touzhu_rk_hm = explode('[H]',$number);
        $status = 1; //数据可以提交数据库
        //开启事务
        Db::startTrans();
        foreach($touzhu_rk_hm as $yzges) {
            $touzhu_rk_danciyz = explode('[SH]',$yzges);
            if(count($touzhu_rk_danciyz == 2)) {
                $tz_split = explode('[G]',$touzhu_rk_danciyz[1]);

                if(count($tz_split) == 8) {
                    //获取用户当前状态信息
                    $user_info = Db::name('username')->field('username,je,dml,tzzje,zyh_tzzje')->where('id',$this->user_all['id'])->find();
                    
                    //限制返点范围
                    if($tz_split[6] > $fandian) $tz_split[6] = $fandian;
                    if($tz_split[6] < 0) $tz_split[6] = 0;
                    //返点应扣除金额
                    $fandian_je = $tz_split[2] / 100 * $tz_split[6];

                    //计算返点、打码量、投注金额等信息
                    $touzhu_true_je = $tz_split[2] - $fandian_je;
                    $user_money = $user_info['je'] - $touzhu_true_je;
                    $use_dml = $user_info['dml'] - $touzhu_true_je;
                    $user_tzzje = $user_info['tzzje'] + $touzhu_true_je;
                    $zyh_tzzje = $user_info['zyh_tzzje']+$touzhu_true_je;
                    if($use_dml < 0) $use_dml = 0;
                    //查看是否升级

                    //将注单写入数据库
                    try {
                        if($checks['id'] == '173') {
                            $zmgg = array('正码1'=>' ','正码2'=>' ','正码3'=>' ','正码4'=>' ','正码5'=>' ','正码6'=>' ');
                            $touzhu_zmgg = explode(',',$tz_split[0]);
                            $touzhu_zmgg = array_map('trim',$touzhu_zmgg);
                            foreach ($touzhu_zmgg as $v) {
                                $split_zmgg = explode('_',$v);
                                $zmgg[$split_zmgg[0]] = $split_zmgg[1];
                            }
                            ksort($zmgg);
                            $zmgg_str = join(',',$zmgg);
                            $tz_split[0] = $zmgg_str;
                        }
                        //扣除用户金额 // 扣除打码量 // 增加用户投注量
                        if( !model('Username')->updateUserBetInfo($user_money,$use_dml,$user_tzzje,$user_info['username'],$zyh_tzzje) ){
                        	throw new Exception("ERROR");
                        }
                        //将新投注插入未结算列表
                        if( !model('TouzhuListNo')->setBetInfoNo($czid,$periods,$tz_split[0],$tz_split[2],$tz_split[4],$tz_split[3],$user_info['username'],$user_money,0,0,$checks['id'],$tz_split[5],$tz_split[6],$fandian_je,0,0,$tz_split[1],time()) ){
                            throw new Exception("ERROR");
                        }
                        
                    } catch (\Exception $e) {
                        // 回滚事务
                        $status = 0; //有错不可提交数据库
                        break;
                    }
                }
            }
        }
        if( 0==$status ){
            Db::rollback();
            return '下注失败请重试！';
        }else{
            Db::commit();
            return '第'.$periods.'期投注成功！';
        }
    }
    
    /**
     * @Purpose 手机下注入库
     * @Time 2017-11-29
     */
    public function lotteryBettingStockMobile()
    {

        if(!$this->user_all['id']) {
            return 'notlogin';
        }
        if( 1==intval($this->user_all['touzhu_open']) ){
            return '未开通投注权限';
        }
        //接收参数
        $czid = input('czid') ? intval(input('czid')) : '';
        $number = input('number') ? input('number') : '';
        $periods = input('periods') ? input('periods') : '';

        if(!$czid || !$number || !$periods) {
            $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,'参数不完整');
            return '非法操作，已被记录！';
        }
        //-------------------------------------------------期号验证------------------------------------------------------------------//
        $qh = Db::name('kjjg_list')->where(['czid'=>$czid,'jztime'=>['>',time()],'kjjg'=>0,'iftz'=>0])->order('qihao','ASC')->find();
        if($qh['qihao']){
        	if($periods!=$qh['qihao']){
        		$periods = $qh['qihao'];
        		//return '期号出错，请刷新页面';
        	}
        }else{
        	$qihao = $this->qihaoNext($czid);
        	if($periods!=$qihao[0]){
        		$periods = $qihao[0];
        		//return '期号出错，请刷新页面';
        	}
        }
        //-------------------------------------------------期号验证------------------------------------------------------------------//
        //验证投注期数是否已经截止投注
        $touzhu_info = Db::name('kjjg_list')->field('jztime,kjjg')->where(['czid'=>$czid,'qihao'=>$periods])->find();
        $close_time = Db::name('caipai_list')->where('id',$czid)->value('cp_fp_time');
        $close_time = $close_time ? $close_time : 30;
    
        /* if(!($touzhu_info['jztime'] > time() && ($touzhu_info['kjjg'] == '0'))) {
            return '已经封盘，请下一期再投！';
        } */
    
        //查询当前彩种返点
        $lottery_type_info = Db::name('lottery_classify')->field('id,fandian')->where("czids REGEXP '(^|,){$czid}($|,)'")->find();
        $fandian = intval($lottery_type_info['fandian']);
    
        //定义公共变量
        $all_touzhu_zhushu = 0;
        $all_touzhu_jine = 0;
    
        /* 验证投注号码格式是否正确 */
        $touzhu_code_hm = explode('[H]',$number);
        foreach($touzhu_code_hm as $yzges) {
            $touzhu_code_danciyz = explode('[SH]',$yzges);
            if(count($touzhu_code_danciyz == 2)) {
                $touzhu_code_1 = explode('[G]',$touzhu_code_danciyz[1]);
                if(count($touzhu_code_1) == 8) {
                    if(!is_numeric($touzhu_code_1[2])) {
                        return '投注金额错误！';
                    }
                    $all_touzhu_jine = $all_touzhu_jine + $touzhu_code_1[2];
                    $touzhu_code_1[0] = trim($touzhu_code_1[0]);
                    $touzhu_code_1[5] = trim($touzhu_code_1[5]);

                    //查询验证所需信息
                    $checks = Db::name('play_classify')
                    ->field('id,class_name_mini,min_num,max_num,peilv_ids,max_money')
                    ->where('id',$touzhu_code_1[7])
                    ->find();
                    $play_way = $checks['class_name_mini'];
                    
                    //验证最大投注金额
                    if($checks['max_money']) {
                        $max_money = 0;
                        if($touzhu_code_1[1] == '1') $max_money = $checks['max_money'];
                        if($touzhu_code_1[1] == '2') $max_money = $checks['max_money'] * 10;
                        if($touzhu_code_1[1] == '3') $max_money = $checks['max_money'] * 100;
                        if($touzhu_code_1[4] > $max_money) return "超出单注最大投注金额！";
                    }
                    
                    //获取赔率信息
                    if($checks['id'] != '173' && $checks['id'] != '242') {
                        if(count(explode(',',$checks['peilv_ids'])) == 1) {
                            $peilv_info = Db::name('peilv')->where(['lottery_class_id'=>$lottery_type_info['id'],'id'=>$checks['peilv_ids']])->find();
                        } else {
                            //多赔率组合玩法特殊处理
                            if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16' || $checks['id'] == '188' || $checks['id'] == '204') {
                                $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where('lottery_class_id',$lottery_type_info['id'])->where('id','IN',$checks['peilv_ids'])->select();
                            } else {
                                //六合彩类赔率特殊查询规则
                                if($czid == 9 && $checks['id']) {
                                    if($checks['id'] == '172')  {
                                        $hm_split = explode('_',$touzhu_code_1[0]);
                                        $touzhu_code_1[0] = $hm_split[1];
                                    }
                                    $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'peilv_name'=>$touzhu_code_1[0],'spare'=>$play_way])->find();
                                } else {
                                    $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'peilv_name'=>$touzhu_code_1[0]])->find();
                                }
                            }
                        }
                    }
    
                    //获取赔率信息(正码过关)
                    if($checks['id'] == '173') {
                        $peilv_info = [];
                        $touzhu_zmgg = explode(',',$touzhu_code_1[0]);
                        $touzhu_zmgg = array_map('trim',$touzhu_zmgg);
                        foreach ($touzhu_zmgg as $v) {
                            $split_zmgg = explode('_',$v);
                            $peilv_info[] = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'spare'=>$play_way])->where('peilv_name',$split_zmgg[1])->find();
                        }
                    }
    
                    //获取赔率信息(合肖)
                    if($checks['id'] == '242') {
                        $peilv_info = [];
                        $touzhu_hx = explode(' ',$touzhu_code_1[0]);
                        foreach ($touzhu_hx as $v) {
                            if(trim($v)) {
                                $peilv_info[] = Db::name('peilv')->field('zgpl,zdpl')->where(['lottery_class_id'=>$lottery_type_info['id'],'spare'=>$play_way])->where('peilv_name',$v)->find();
                            }
                        }
                    }
//return $peilv_info;
//return json_encode($peilv_info);
                    //验证赔率
                    if($checks['id'] != '173' && $checks['id'] != '242') {
                        //多赔率组合玩法特殊验证
                        if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16'  || $checks['id'] == '188'  || $checks['id'] == '204') {
                            $peilv_true = '';
                            foreach($peilv_info as $kpi=>$pi) {
                                $peilvs_true = $pi['zdpl'] + ($pi['zgpl'] - $pi['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                                $peilvs_true = sprintf('%.2f',$peilvs_true);
                                $peilv_true .= $peilvs_true . '|';
                            }
                        } else {
                            $peilv_true = $peilv_info['zdpl'] + ($peilv_info['zgpl'] - $peilv_info['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = sprintf('%.2f',$peilv_true);
                        }
                    }
    
                    if($checks['id'] == '173') {
                        //正码过关验证
                        $peilv_true = 1;
                        foreach ($peilv_info as $k => $v) {
                            $peilv_tmp = $v['zdpl'] + ($v['zgpl'] - $v['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = $peilv_true * $peilv_tmp;
                        }
                        $peilv_true = sprintf('%.2f',$peilv_true);
                    }
    
                    if($checks['id'] == '242') {
                        //合肖验证
                        $peilv_true = 0;
                        foreach ($peilv_info as $k => $v) {
                            $peilv_tmp = $v['zdpl'] + ($v['zgpl'] - $v['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                            $peilv_true = $peilv_true + $peilv_tmp;
                        }
                        
                        $peilv_true = $peilv_true / count($peilv_info) / count($peilv_info);
                        $peilv_true = sprintf('%.2f',$peilv_true);
                    }
//return $peilv_true."#".$touzhu_code_1[5];
                    if(floatval($peilv_true) != floatval($touzhu_code_1[5])) {
                        $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'A1');
                        return '非法操作A1，已被记录！';
                    }
                    
                    $duidehm = ''; //初始化号码验证，必须放在此处
                    //验证号码是否超限
                    $touzhu_code_2 = explode(',',$touzhu_code_1[0]);
                    $touzhu_code_2 = array_map('trim',$touzhu_code_2);
                    if(count($touzhu_code_2) > 1) {
                        foreach($touzhu_code_2 as $yzges_1) {
                            $touzhu_code_3 = explode(' ',$yzges_1);
                            foreach($touzhu_code_3 as $yzges_2) {
                                if((floor($yzges_2)>=$checks['min_num']) && (floor($yzges_2)<=$checks['max_num'])) {
                                    $duidehm .= $yzges_2;
                                }
                            }
                        }
                    } else {
                        if((floor($touzhu_code_2[0])>=$checks['min_num']) && (floor($touzhu_code_2[0])<=$checks['max_num'])) {
                            $duidehm = $touzhu_code_2[0];
                        }
                    }
    
                    $hm_only = str_replace([',',' '],'',$touzhu_code_1[0]);
                    $duidehm = str_replace([',',' '],'',$duidehm);
//return $hm_only."#".$duidehm;
                    if($duidehm != $hm_only) {
                        $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'A2');
                        return '非法操作A2，已被记录！';
                    }
                }
    
                //验证投注注数
                $tzzs = touzhu_hm_code_zhushu($checks['id'],$touzhu_code_1[0],$lottery_type_info['id']);
//return $tzzs;
                if(($touzhu_code_1[3] != $tzzs) || !$tzzs) {
                    $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'B');
                    return '非法操作B，已被记录！';
                }
            }
        }

        //验证投注金额
        $code_touzhu_jine = touzhuhaoma_jine_code($number);
//return $all_touzhu_jine."#".$code_touzhu_jine;
        if($all_touzhu_jine != $code_touzhu_jine) {
            $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way,'C');
            return "非法操作C，已被记录！";
        }
    
        //验证用户金额
        if($this->user_all['je'] < $all_touzhu_jine) {
            return '账号余额不足，请充值后再下注！';
        }
        $touzhu_rk_hm = explode('[H]',$number);
        //开启事务
        $status = 1; //数据可以提交数据库
        Db::startTrans();
        foreach($touzhu_rk_hm as $yzges) {
            $touzhu_rk_danciyz = explode('[SH]',$yzges);
            if(count($touzhu_rk_danciyz == 2)) {
                $tz_split = explode('[G]',$touzhu_rk_danciyz[1]);

                if(count($tz_split) == 8) {
                    //获取用户当前状态信息
                    $user_info = Db::name('username')->field('username,je,dml,tzzje,zyh_tzzje')->where('id',$this->user_all['id'])->find();
                    
                    //查询验证所需信息
                    $checks = Db::name('play_classify')->field('id')->where('id',$tz_split[7])->find();
    
                    //限制返点范围
                    if($tz_split[6] > $fandian) $tz_split[6] = $fandian;
                    if($tz_split[6] < 0) $tz_split[6] = 0;
                    //返点应扣除金额
                    $fandian_je = $tz_split[2] / 100 * $tz_split[6];
    
                    //计算返点、打码量、投注金额等信息
                    $touzhu_true_je = $tz_split[2] - $fandian_je;
                    $user_money = $user_info['je'] - $touzhu_true_je;
                    $use_dml = $user_info['dml'] - $touzhu_true_je;
                    $user_tzzje = $user_info['tzzje'] + $touzhu_true_je;
                    $zyh_tzzje = $user_info['zyh_tzzje']+$touzhu_true_je;
                    if($use_dml < 0) $use_dml = 0;
    
                    //将注单写入数据库
                    try {
                        if($checks['id'] == '173') {
                            $zmgg = array('正码1'=>' ','正码2'=>' ','正码3'=>' ','正码4'=>' ','正码5'=>' ','正码6'=>' ');
                            $touzhu_zmgg = explode(',',$tz_split[0]);
                            $touzhu_zmgg = array_map('trim',$touzhu_zmgg);
                            foreach ($touzhu_zmgg as $v) {
                                $split_zmgg = explode('_',$v);
                                $zmgg[$split_zmgg[0]] = $split_zmgg[1];
                            }
                            ksort($zmgg);
                            $zmgg_str = join(',',$zmgg);
                            $tz_split[0] = $zmgg_str;
                        }
                        //扣除用户金额 // 扣除打码量 // 增加用户投注量
                        if( !model('Username')->updateUserBetInfo($user_money,$use_dml,$user_tzzje,$user_info['username'],$zyh_tzzje) ){
                        	throw new Exception("ERROR");
                        }
                        //将新投注插入未结算列表
                        if( !model('TouzhuListNo')->setBetInfoNo($czid,$periods,$tz_split[0],$tz_split[2],$tz_split[4],$tz_split[3],$user_info['username'],$user_money,0,0,$checks['id'],$tz_split[5],$tz_split[6],$fandian_je,0,0,$tz_split[1],time(),2) ){
                            throw new Exception("ERROR");
                        }
                        
                    } catch (\Exception $e) {
                        $status = 0;
                        break;
                    }
                }
            }
        }
        //清除投注cookie信息
        if($czid==9){
            //sessionStorage.clear();
            @file_put_contents('./cookie/cookie'.$this->user_all['username'].'.txt',"");
        }else{
            foreach ($_COOKIE as $k => $v){
                Cookie::clear('wanfa_tzhm_');
            }
        }
        if( 0==$status ){
            Db::rollback();
            return '下注失败请重试！';
        }else{
            Db::commit();
            return '第'.$periods.'期投注成功！';
        }
    }
	/**
	 * 追号接口
	 * @return string
	 */
    public function lotteryZhuihao(){
    	
    	//参数    彩种id，彩种期号，投注期数
    	$czid=input('czid','');
    	$qihao = input('qihao','');
    	$qishu = input('qishu','');
    	$jine = input('jine',0);
    	if(!$czid || !$qihao || !$qishu){
    		return '参数缺失';
    	}
    	$qh =array('jine'=>$jine,'year'=>date('m-d'),'hour'=>date('H:i:s'),'datas'=>[]);
    	$qh['datas'] = $this->qihaoNext($czid,$qishu);
    	if($qihao==$qh['datas'][0]){
    		$qh['datas'] = $this->qihaoNext($czid,$qishu+1);
    		//unset($qh['datas'][0]);
    	}
    	return json_encode($qh,JSON_UNESCAPED_UNICODE);
    }
    
    /**
     * @Purpose 追号入库
     * @Time 2017-11-30
     */
    public function lotteryBettingChase()
    {
        //开启事务
        
        if(!$this->user_all['id']) {
            return 'notlogin';
        }
        if( 1==intval($this->user_all['touzhu_open']) ){
            return '未开通投注权限';
        }
        //接收参数
        $czid = input('czid') ? intval(input('czid')) : '';
        $number = input('number') ? input('number') : '';
        $play_way = input('play_way') ? input('play_way') : '';
        $qihao = input('qihao') ? input('qihao') : '';
        $periods = input('periods') ? input('periods') : '';
        $multiple = input('multiple') ? input('multiple') : '';
        $money = input('money') ? input('money') : '';
        $method = input('method') ? input('method') : 1;
        //echo $czid.'-'.$number .'-'.$play_way.'-'.$periods.'-'.$multiple.'-'.$money .'-'.$qihao;exit;
        if(!$czid || !$number || !$play_way || !$periods || !$multiple || !$money || !$qihao) {
            $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$play_way);
            return '非法操作，已被记录！';
        }

        $zhuohao_qishu_array = explode('|',$periods);
        $zhuohao_beishu_array = explode('|',$multiple);
        if(count($zhuohao_qishu_array) != count($zhuohao_beishu_array)) {
            return '操作失败请刷新重试！';
        }
        $kjjg = Db::name('kjjg_list')->alias('kl')->join('__CAIPAI_LIST__ cp','cp.id=kl.czid')->field('kl.jztime,cp.cp_fp_time')->where('czid',$czid)->where('qihao',$qihao)->find();
        $times = floor($kjjg['jztime']);
       /*  if($times <= time()){
        	return '当期已封盘，请刷新重新追号';
        } */

        //查询当前彩种返点
        $lottery_type_info = Db::name('lottery_classify')->field('id,fandian')->where("czids REGEXP '(^|,){$czid}($|,)'")->find();
        $fandian = intval($lottery_type_info['fandian']);
        
        //查询验证所需信息
        
		
        //定义公共变量
        $all_touzhu_zhushu = 0;
        $all_touzhu_jine = 0;

        /* 验证投注号码格式是否正确 */
        /* 验证投注号码格式是否正确 */
        $touzhu_code_hm = explode('[H]',$number);
        foreach($touzhu_code_hm as $yzges) {
            $touzhu_code_danciyz = explode('[SH]',$yzges);
            if(count($touzhu_code_danciyz) == 2) {
                $touzhu_code_1 = explode('[G]',$touzhu_code_danciyz[1]);
                $checks = Db::name('play_classify')->alias('pc')
			                ->join('__WAY_CLASSIFY__ wc','pc.way_class_id=wc.id')
			                ->field('pc.id,pc.min_num,pc.max_num,pc.peilv_ids,pc.max_money')
			                ->where('wc.lottery_class_id',$lottery_type_info['id'])
			                ->where('pc.id',$touzhu_code_1[7])
			                ->find();
                if(count($touzhu_code_1) == 8) {
                    if(!is_numeric($touzhu_code_1[2])) {
                        return '投注金额错误！';
                    }
                    $all_touzhu_jine = $all_touzhu_jine + $touzhu_code_1[2];
                    $all_touzhu_zhushu = $all_touzhu_zhushu+$touzhu_code_1[3];
                    $touzhu_code_1[0] = trim($touzhu_code_1[0]);
                    $touzhu_code_1[5] = trim($touzhu_code_1[5]);
                    
                    //验证最大投注金额
                    if($checks['max_money']) {
                        $max_money = 0;
                        if($touzhu_code_1[1] == '1') $max_money = $checks['max_money'];
                        if($touzhu_code_1[1] == '2') $max_money = $checks['max_money'] * 10;
                        if($touzhu_code_1[1] == '3') $max_money = $checks['max_money'] * 100;
                        if($touzhu_code_1[4] > $max_money) return "超出单注最大投注金额！";
                    }

                //获取赔率信息
                if(count(explode(',',$checks['peilv_ids'])) == 1) {
                    $peilv_info = Db::name('peilv')->where(['lottery_class_id'=>$lottery_type_info['id'],'id'=>$checks['peilv_ids']])->find();
                } else {
                    //组合玩法赔率特殊处理
                    if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16' || $checks['id'] == '188'  || $checks['id'] == '204') {
                        $peilv_info = Db::name('peilv')->field('zgpl,zdpl')->where('lottery_class_id',$lottery_type_info['id'])->where('id','IN',$checks['peilv_ids'])->select();
                    } else {
                        $peilv_info = Db::name('peilv')->where(['lottery_class_id'=>$lottery_type_info['id'],'peilv_name'=>$touzhu_code_1[0]])->find();
                    }
                }

                //验证赔率
                if($checks['id'] == '2' || $checks['id'] == '10' ||$checks['id'] == '16' || $checks['id'] == '188'  || $checks['id'] == '204') {
                    //组合玩法赔率特殊验证
                    $peilv_true = '';
                    foreach($peilv_info as $kpi=>$pi) {
                        $peilvs_true = $pi['zdpl'] + ($pi['zgpl'] - $pi['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                        $peilvs_true = sprintf('%.2f',$peilvs_true);
                        $peilv_true .= $peilvs_true . '|';
                    }
                } else {
                    $peilv_true = $peilv_info['zdpl'] + ($peilv_info['zgpl'] - $peilv_info['zdpl']) / ($fandian ? $fandian : 1) * ($fandian - $touzhu_code_1[6]);
                    $peilv_true = sprintf('%.2f',$peilv_true);
                }
               //return $peilv_true.'###'.$touzhu_code_1[5];
                if($peilv_true != $touzhu_code_1[5]) {
                    $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$touzhu_code_1[7],'A1');
                    return '非法操作A，已被记录！';
                }
                
                $duidehm = ''; //初始化号码验证，必须放在此处
                //验证号码是否超限
                $touzhu_code_2 = explode(',',$touzhu_code_1[0]);
                $touzhu_code_2 = array_map('trim',$touzhu_code_2);
                if(count($touzhu_code_2) > 1) {
                    foreach($touzhu_code_2 as $yzges_1) {
                        $touzhu_code_3 = explode(' ',$yzges_1);
                        foreach($touzhu_code_3 as $yzges_2) {
                            if((floor($yzges_2)>=$checks['min_num']) && (floor($yzges_2)<=$checks['max_num'])) {
                                $duidehm .= $yzges_2;
                            }
                        }
                    }
                } else {
                    if((floor($touzhu_code_2[0])>=$checks['min_num']) && (floor($touzhu_code_2[0])<=$checks['max_num'])) {
                        $duidehm = $touzhu_code_2[0];
                    }
                }
                
                $hm_only = str_replace([',',' '],'',$touzhu_code_1[0]);
                $duidehm = str_replace([',',' '],'',$duidehm);

                if($duidehm != $hm_only) {
                    $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$touzhu_code_1[7],'A2');
                    return '非法操作A2，已被记录！';
                }
            }

            //验证投注注数
            $tzzs = touzhu_hm_code_zhushu($checks['id'],$touzhu_code_1[0],$lottery_type_info['id']);
            //return $tzzs;
            if(($touzhu_code_1[3] != $tzzs) || !$tzzs) {
                $this->weigui_touzhu($this->user_all['username'],$number,$periods,$czid,$touzhu_code_1[7],'B');
                return '非法操作B，已被记录！';
            }
        }
    	}
        
        //验证投注金额
        $code_touzhu_jine = touzhuhaoma_jine_code($number);
        if($all_touzhu_jine != $code_touzhu_jine) {
            return "非法操作C，已被记录！";
        }

        //验证追号总金额
        $zongzhuihaojine = 0;
        for($zhz=0;$zhz<count($zhuohao_beishu_array);$zhz++) {
            $zongzhuihaojine = ($zongzhuihaojine * 100 + $code_touzhu_jine * $zhuohao_beishu_array[$zhz] * 100) / 100;
        }
        $zongzhuihaojine = floor($zongzhuihaojine);
        $money = floor($money);

        if($zongzhuihaojine != $money) {
            return '非法操作，已被记录！';
        }
        
        //验证用户总金额
        if($this->user_all['je'] < $zongzhuihaojine) {
            return '账户金额不足，请充值后在操作！';
        }

        $youxiao_zhuihao_qishu = 0;
        for($xr=0;$xr<count($zhuohao_qishu_array);$xr++) {
            $ifyijicunsk = Db::name('kjjg_list')->where(['czid'=>$czid,'qihao'=>$zhuohao_qishu_array[$xr]])->find();
            if(!$ifyijicunsk['id']) {
                $touzhu_rk_hm = explode('[H]',$number);
                foreach($touzhu_rk_hm as $yzges) {
                    $touzhu_rk_danciyz = explode('[SH]',$yzges);
                    if(count($touzhu_rk_danciyz == 2)) {
                        $touzhu_rk_1 = explode('[G]',$touzhu_rk_danciyz[1]);
                        $checkd = Db::name('play_classify')->alias('pc')
	                        ->join('__WAY_CLASSIFY__ wc','pc.way_class_id=wc.id')
	                        ->field('pc.id,pc.min_num,pc.max_num,pc.peilv_ids,pc.max_money')
	                        ->where('wc.lottery_class_id',$lottery_type_info['id'])
	                        ->where('pc.id',$touzhu_rk_1[7])
	                        ->find();
                        if(count($touzhu_rk_1) == 8) {
                            //获取用户当前状态信息
                            $user_info = Db::name('username')->field('username,je,dml,tzzje,zyh_tzzje')->where('id',$this->user_all['id'])->find();

                            $touzhu_rk_1[2] = floor($touzhu_rk_1[2] * 100) / 100;
                            $touzhu_rk_1[4] = floor($touzhu_rk_1[4] * 100) / 100;
                            $touzhu_rk_1[2] = $touzhu_rk_1[2] * $zhuohao_beishu_array[$xr];
                            $touzhu_rk_1[4] = $touzhu_rk_1[4] * $zhuohao_beishu_array[$xr];
                            //限制返点范围
                            if($touzhu_rk_1[6] > $fandian) $touzhu_rk_1[6] = $fandian;
                            if($touzhu_rk_1[6] < 0) $touzhu_rk_1[6] = 0;
                            //返点应扣除金额
                            $touzhu_rk_fandian_jine = $touzhu_rk_1[2] / 100 * $touzhu_rk_1[6];
                            
                            //计算返点、打码量、投注金额等信息
                            $touzhu_benqi_zhenshi_jine = $touzhu_rk_1[2] - $touzhu_rk_fandian_jine;
                            $touzhu_hou_yue = $user_info['je'] - $touzhu_benqi_zhenshi_jine;
                            $touzhu_username_dml = $user_info['dml'] - $touzhu_benqi_zhenshi_jine;
                            if($touzhu_username_dml < 0)  $touzhu_username_dml = 0;
                            $touzhu_username_touzhuzje = $user_info['tzzje'] + $touzhu_benqi_zhenshi_jine;
                            $youxiao_zhuihao_qishu = $youxiao_zhuihao_qishu + $touzhu_benqi_zhenshi_jine;
                            $zyh_tzzje = $user_info['zyh_tzzje'] + $touzhu_benqi_zhenshi_jine;
                            $status = 1;
                            Db::startTrans();
                            try {
                            	//扣除用户金额 // 扣除打码量 // 增加用户投注量
                            	if(!model('Username')->updateUserBetInfo($touzhu_hou_yue,$touzhu_username_dml,$touzhu_username_touzhuzje,$user_info['username'],$zyh_tzzje)){
                            		throw new Exception("ERROR");
                            	}
                                //将新追号投注插入追号列表
                                if(!model('TouzhuListZh')->setBetInfoZh($czid,$zhuohao_qishu_array[$xr],$touzhu_rk_1[0],$touzhu_rk_1[2],$touzhu_rk_1[4],$touzhu_rk_1[3],$this->user_all['username'],$touzhu_hou_yue,0,0,$checkd['id'],$touzhu_rk_1[5],$touzhu_rk_1[6],$touzhu_rk_fandian_jine,0,0,$touzhu_rk_1[1],time(),$method)){
                                	throw new Exception("ERROR");
                                }
                               
                            } catch (\Exception $e) {
                                $status = 0;
                       			 break;
                            }
                        }
                    }
                }
            }
        }
        //清除投注cookie信息
        foreach ($_COOKIE as $k => $v){
            Cookie::clear('wanfa_tzhm_');
        }
        if( 0==$status ){
        	Db::rollback();
        	return '下注失败请重试！';
        }else{
        	Db::commit();
        	return '第'.$periods.'期投注成功！';
        }
        return '成功追号！';
    }

    /**
     * @Purpose 网站试玩功能
     * @Time 2017-11
     */
    public function tryPlay()
    {
        $reg_pass = input('post.reg_pass') ? input('post.reg_pass') : '';
        $reg_pass_con = input('post.reg_pass_con') ? input('post.reg_pass_con') : '';
        $code = input('post.code') ? input('post.code') : '';
        if(!$reg_pass) {
            js_tishi('请完善信息后注册！','/index/Index/tryPlay');exit;
        }
        //判断试玩功能是否开启
        $swsm = Db::name('xt_shiwan')->find();
        if($swsm['open'] == 1) {
            //判断两次密码是否一致
            if($reg_pass !== $reg_pass_con) {
                js_tishi('两次密码不一致！','/index/Index/tryPlay');exit;
            }

            $username = $swsm['qianzhui'];
            $yuscount = '';
            for($t=1;$t<=$swsm['swcd'];$t++) {
                $yuscount .= rand(0,9);
            }
            $username = $username.$yuscount;
            $password = md5($reg_pass);
            $login_key = suiji_zifu(15);
            
            //获得IP并解析地址
            $login_ip = $this->login_ip;

           /*  $ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$login_ip}");
            if($ip) {
                $ip = json_decode($ip,true);
                $position = $ip['data']['country'].' '.$ip['data']['region'].' '.$ip['data']['city'];
            } */

            //写入账号
            model('Username')->setTryPlayUser($username,$password,$swsm['je'],'0','试玩',time(),$login_ip,'','1','1',$login_key,'0',1);
            //设置用户cookie
            cookie("username",$username);
            cookie("password",$password);
            cookie("login_key",$login_key);
            if(computer_or_mobile() == 'mobile') {
                js_tishi('申请成功！','/mobile/Bet/index');
            } else {
                js_tishi('申请成功！','/index/Bet/index');
            }
        } else {
            js_tishi('系统未开启试玩功能！','/index/Bet/index');
        }
    }
    /**
     * 会员等级晋升
     */
    public function upgrade(){
        if (strtotime(date('Y-m-d 02:00:00')) <= time() && strtotime(date('Y-m-d 03:00:00')) >= time()) {
    		Db::startTrans();
	    	$lv_list = Db::name('us_class')->order('czl asc')->field('id,class_name,dividend,czl,xml')->select();
	    	$users = Db::name('username')->where(array('nbzh'=>0,'swzh'=>0))->field('username,je,us_class,czzje,tzzje')->select();
	    	foreach($users as $user){
	    	    $self_class = array_search($user['us_class'], array_column($lv_list, 'id'));
	    	    $us_lv_list = array_slice($lv_list,$self_class+1);
	    	    $val = $user['us_class'];
		    	foreach ($us_lv_list as $lv){
		    		if(floor($user['czzje'])>=floor($lv['czl']) && floor($user['tzzje']) >= floor($lv['xml'])){
		    			$val = $lv['id'];
		    			$dividend = $lv['dividend'];
		    		}else{
		    		    break;
		    		}
		    		
		    	}
		    	
		    	if($user['us_class'] != $val){
		    	    
		    		try {
			    		if($dividend > 0){
			    		   $save = Db::name('username')->where('username', $user['username'])->setInc('je', $dividend);
			    		   
	        	           $data = array();
	        	           $zje = $user['je']+$dividend;
	        	           $data['username'] = $user['username'];
	        	           $data['user_class'] = $val;
	        	           $data['cjje'] = $dividend;
	        	           $data['fstime'] = time();
	        	           $data['beizhu'] = '系统赠送，会员等级晋升赠送彩金';
	        	           $data['czadmin'] = '系统赠送';
	        	           $data['cjhje'] = sprintf("%.2f",$zje);
	        	           Db::name('caijin_list')->insert($data);
			    		}
			    		
		    			Db::name('username')->where('username',$user['username'])->setField('us_class',$val);
		    			$us = Db::name('username')->alias('u')->join('__US_CLASS__ uc','uc.id=u.us_class')->field('uc.class_name')->where('c.username', $user['username'])->find();
		    			$data = array();
		    			$data['username'] = $user['username'];
		    			$data['test'] = '恭喜您成功晋级为'.$us['class_name'].'。晋级时间为'.date('Y-m-d H:i:s');
		    			$data['xx_time'] = time();
		    			$data['ifdq'] = 0;
		    			Db::name('xiaoxi')->insert($data);
		    			Db::commit();
		    			echo '晋级成功'.'<br/>';
		    		} catch (\Exception $e) {
		    			// 回滚事务
		    			Db::rollback();
		    			echo '参数错误请重试！';
		    		}
		    		 
		    	}else{
		    		echo '未达到晋级标准'.$user['username'].'<br/>';
		    	}
	    	}
    	 }else{
    		echo '时间未到晋级时间';
    	} 
    	
    }


    /**
     * 撤单
     */
    public function colourfulWithdrawal(){
    	Db::startTrans();
    	$id = input('id');

    	$touzhu = Db::name('touzhu_list_no')->where('id',$id)->find();
    	$where = array('czid'=>$touzhu['czid'],'qihao'=>$touzhu['qihao']);
    	$je = Db::name('username')->where('username',$this->user_all['username'])->value('je');
    	$kjjg = Db::name('kjjg_list')->alias('k')
    			->join('__CAIPAI_LIST__ c','c.id=k.czid')
    			->field('k.jztime,c.cp_fp_time')	
    			->where('k.czid',$touzhu['czid'])->where('k.qihao',$touzhu['qihao'])->find();
    	$fptime = $kjjg['jztime']-$kjjg['cp_fp_time'];

    	unset($touzhu['rktime']);
    	$touzhu['rktime'] = time();
    	$touzhu['cdqje'] = $je;
    	
    	if($fptime>time()){
	    	try {
		    	if(!Db::name('touzhu_list_cd')->data($touzhu)->insert()){throw new \Exception(3);}
		    	if(!Db::name('username')->where('username',$touzhu['username'])->update(array('je'=>['exp',"je+'{$touzhu['tzje']}'"],'tzzje'=>['exp',"tzzje-'{$touzhu['tzje']}'"]))){
		    		throw new \Exception(3);
		    	}
		    	if(!Db::name('touzhu_list_no')->where('id',$id)->delete()){
		    		throw new \Exception(3);
		    	}
		    	Db::commit();
		    	return 1;//撤单成功
	    	}catch (\Exception $e) {
	            Db::rollback();
	            return 3;//撤单失败
	        }
    	}else{
    		return 2;//已封盘无法撤单
    	}
    	
    }
    /**
     * 时间间隔彩票
     */
    public function timeIntval(){
    	$uid = input('post.uid');
    	$jztime = input('jzt');
    	$qihao_old = input('qihao');
    	$dqtime = array();
    	$time = Db::name('caipai_list')->where('id',$uid)->field('time,cp_fp_time')->find();
    	$tm = date('H:i:s',$time['time']+time()-10);
    	if($uid == 1 && ($tm >= '22:00:00' || ($tm>='00:00:00' && $tm<='01:55:40'))){
    			$tm = date('H:i:s',time()+300-10);
    	}
    	if($uid==9){
    		$sj = Db::name('time')->where('czid',$uid)->limit(1)->select();
    	}else{
    		$sj = Db::name('time')->where('czid',$uid)->where('jztime','>',$tm)->order('jztime','ASC')->limit(10)->select();
    	}
    	$time_min = Db::name('time')->field('MIN(qihao),czid')->group('czid')->column('qihao,jztime','czid');
    	$time_min_xyft = Db::name('time')->where(['czid'=>61])->field('qihao,jztime')->order("jztime ASC")->find();
    	$xyft_time_qh = Db::name('time')->where(['czid'=>61])->column("jztime,qihao");
    	foreach ($sj as $key=>$val){
    		if(empty($sj)){
    			if( 61==intval($uid) ){//幸运飞艇
    				$val['jztime'] = $time_min_xyft['jztime'];
    				$val['qihao']  =$time_min_xyft['qihao'];
    			}elseif( 1==intval($uid) ){//重庆时时彩
    				$val['jztime'] = '00:00:00';
    				$val['qihao']  = '120';
    			}else{
    				$val['jztime'] = $time_min[$uid]['jztime'];
    				$val['qihao']  = $time_min[$uid]['qihao'];
    			}
    			$sz_time = strtotime(date("Y-m-d",strtotime("+1 day")) . ' ' . $val['jztime']);
    		
    		}else {
    				
    			$sz_time = strtotime(date('Y-m-d') . ' ' . $val['jztime']);
    		}
    		switch ( intval($uid) ) {
    			case 1:
    				//重庆时时彩
    				if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    				if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    				$qihao = (120==intval($val['qihao'])) ? date('Ymd', time()).$val['qihao'] : date('Ymd', $sz_time).$val['qihao'];
    				break;
    			case 62:
    				if ($val['qihao'] == 0 && $val['jztime'] = '00:00:00') {
    					$qihao = date('YmdHi', $sz_time);
    				} else {
    					$qihao = date('YmdHi', strtotime(date('Y-m-d') . $val['jztime']));
    				}
    				break;
    			case 63:
    				
    			case 72:
    				if($val['qihao']==1440 && $data['jztime']='00:00:00') {
    					$qihao = date('Ymd',strtotime('-1 day')).$val['qihao'];
    				}else{
    				 	if(strlen($val['qihao'])==1){$val['qihao'] = '000'.$val['qihao'];}
        				if(strlen($val['qihao'])==2){$val['qihao'] = '00'.$val['qihao'];}
       					if(strlen($val['qihao'])==3){$val['qihao'] = '0'.$val['qihao'];}
    					$qihao = date('Ymd').$val['qihao'];
    				}
    				break;
    			case 36:
    				//安徽快三
    			case 44:
    				//江苏快三
    			case 8:
    				//天津时时彩彩
    				if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    				if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    				$qihao = date('Ymd', strtotime(date('Y-m-d') . $val['jztime'])) . $val['qihao'];
    				break;
    			case 4:
    				//北京赛车
    			case 5:
    				//排列三
    			case 10:
    				//PC蛋蛋
    			case 7:
    				//上海时时乐
    				$qihao_tmp = $qihao_old + 1+$key;
    				if (strlen($qihao_tmp) == strlen($qihao_old)) {
    					$qihao = $qihao_tmp;
    				} else {
    					$qihao = '0' . $qihao_tmp;
    				}
    				break;
    			
    			case 16:
    				//广东11选5
    			case 28:
    				//山东11选5
    			case 48:
    				//上海时时乐
    			case 25:
    				//江西11选5
    				if ($val['qihao'] < 10) {
    					$val['qihao'] = '0' . $val['qihao'];
    				}
    				$qihao = date('Ymd') . $val['qihao'];
    				break;
    			case 61:
    				//幸运飞艇
    				 $cut_off = strtotime(date('Y-m-d').' '.'04:04:00');
    				if (time() < $cut_off) {
    					$sztime = strtotime(date('Y-m-d', strtotime('-1 day')) . ' ' . $val['jztime']);
    					$qihao = date('Ymd', $sztime) . $val['qihao'];
    				}elseif( time() > strtotime(date('Y-m-d').' '.'23:59:00') ){
    					$sztime = strtotime(date('Y-m-d') . ' ' . $val['jztime']);
    					$qihao = date('Ymd', $sztime) . $val['qihao'];
    				}else{
    					if ($val['qihao'] < 10) $val['qihao'] = '00' . $val['qihao'];
    					if ($val['qihao'] >= 10 && $val['qihao'] < 100) $val['qihao'] = '0' . $val['qihao'];
    					$qihao = date('Ymd', $sz_time) . $val['qihao'];
    				} 
    				break;
    		}

    		$dqtime[] = array('jgtime'=>$time['cp_fp_time']+10,'time'=>$sz_time-$time['cp_fp_time'],'fptime'=>$sz_time-$time['cp_fp_time']-$jztime,'qihao'=>$qihao,'jzt'=>$jztime);
    		
    	}
    	//$shijian = $dqtime-time();
    	return json_encode($dqtime,JSON_UNESCAPED_UNICODE);
    }
    public function timeIntvalTl(){
    	$uid = input('post.uid');
    	$time = Db::name('caipai_list')->where('id',$uid)->field('time,cp_fp_time')->find();
    	$tm = date('H:i:s',$time['time']+time());
    	$sj = Db::name('time')->where('czid',$uid)->where('jztime','>',$tm)->order('jztime','ASC')->find();
    	$dqtime = strtotime(date('Y-m-d').' '.$sj['jztime'])-$time['cp_fp_time']-time();
    	//$shijian = $dqtime-time();
    	return $dqtime;
    }
	/* public function test(){
		$us = Db::name('username')->field('id,tjm')->where('swzh',0)->select();
		foreach ($us as $u){
			$id = $u['id'];
			if(strlen($u['id'])==1){$id='00000'.$u['id'];}
			if(strlen($u['id'])==2){$id='0000'.$u['id'];}
			if(strlen($u['id'])==3){$id='000'.$u['id'];}
			if(strlen($u['id'])==4){$id='00'.$u['id'];}
			if(strlen($u['id'])==5){$id='0'.$u['id'];}
			$data = array('tjm'=>$id);
			Db::name('username')->where('id',$u['id'])->update($data);
			echo 'ok';
		}
	} */

}